package com.digua.base.socket.dispatcher

import com.alibaba.fastjson2.JSON
import com.alibaba.fastjson2.JSONException
import com.digua.base.socket.response.ErrorResponse
import com.digua.base.socket.response.ResponseFactory
import com.digua.base.socket.response.TextResponse


class AppResponseDispatcher<T> : SimpleDispatcher {
    companion object {
        const val JSON_ERROR = 11//JSON 数据格式错误
        const val CODE_ERROR = 12//code 码错误
    }

    val beanClz: Class<T>

    constructor(beanClz: Class<T>) {
        this.beanClz = beanClz
    }

    override fun onMessage(message: String, delivery: ResponseDelivery?) {
        try {
            val result = JSON.parseObject(message, beanClz)
            if (result != null) {
                delivery?.onMessage<T>(message, result)
            } else {
                val errorResponse = ResponseFactory.createErrorResponse()
                errorResponse.errorCode = CODE_ERROR
                val textResponse = ResponseFactory.createTextResponse()
                textResponse.setResponseData(message)
                errorResponse.responseData = textResponse
                errorResponse.reserved = result
                onSendDataError(errorResponse, delivery)
            }
        } catch (e: JSONException) {
            val errorResponse: ErrorResponse = ResponseFactory.createErrorResponse()
            val textResponse: TextResponse = ResponseFactory.createTextResponse()
            textResponse.setResponseData(message ?: "")
            errorResponse.responseData = textResponse
            errorResponse.errorCode = JSON_ERROR
            errorResponse.cause = e
            onSendDataError(errorResponse, delivery)
        }
    }

    /**
     * 统一处理错误信息， 界面上可使用 ErrorResponse#getDescription() 来当做提示语
     */
    override fun onSendDataError(error: ErrorResponse?, delivery: ResponseDelivery?) {
        when (error?.errorCode) {
            ErrorResponse.ERROR_NO_CONNECT -> error.description = "网络错误"
            ErrorResponse.ERROR_UN_INIT -> error.description = "链接未初始化"
            ErrorResponse.ERROR_UNKNOWN -> error.description = "未知错误"
            JSON_ERROR -> error.description = "数据格式异常"
            CODE_ERROR -> error.description = "响应码错误"
        }
        delivery?.onSendDataError(error)
    }
}